package com.rtsapp.server.gamelog.analyze;

import org.apache.log4j.PropertyConfigurator;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.webapp.WebAppContext;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * Created by liwang on 16-7-26.
 */
public class Launcher {


    public static final String CONTEXT = "/";

    private static final String WEBAPP_DIRECTORY  = "webapp";

    private static final String DEFAULT_WEBAPP_PATH = "src/main/webapp";
    /**
     * 创建用于开发运行调试的Jetty Server, 以src/main/webapp为Web应用目录.
     */
    public static Server createServerInSource( int port, String contextPath) throws IOException {
        Server server = new Server();
        // 设置在JVM退出时关闭Jetty的钩子。
        server.setStopAtShutdown(true);

        //这是http的连接器
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(port);
        // 解决Windows下重复启动Jetty居然不报告端口冲突的问题.
        connector.setReuseAddress(false);
        server.setConnectors(new Connector[] { connector });

        String webAppURI =  new ClassPathResource(WEBAPP_DIRECTORY).getURI().toString();
        WebAppContext webContext = new WebAppContext(webAppURI, contextPath);

        //webContext.setContextPath("/");
//        webContext.setDescriptor("src/main/webapp/WEB-INF/web.xml");
        // 设置webapp的位置
//        webContext.setResourceBase(DEFAULT_WEBAPP_PATH);
        webContext.setClassLoader(Thread.currentThread().getContextClassLoader());
        server.setHandler(webContext);
        return server;
    }

    /**
     * 启动jetty服务
     * @param port
     */
    public void startJetty(int port ) throws IOException {
        final Server server = Launcher.createServerInSource( port , CONTEXT);
        try {
            server.stop();
            server.start();
            server.join();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }
    public static void main(String[] args) throws IOException {


        int port = 8080;

        try {
            Properties properties = new java.util.Properties();
            properties.load( new FileInputStream( new File("cfg/app.properties")));
            port = Integer.parseInt( properties.getProperty("port") );
        } catch (Exception e) {
           e.printStackTrace();
        }

        PropertyConfigurator.configure("cfg/log4j.properties");

        new Launcher().startJetty( port );
    }

}
